<template>
	<view class="content">
		<n-form class="form">
			<p>请输入每人支出金额</p>
			<template v-for="(item, index) in formState" :key="index">
				<res-model :item="item" :index="index" @setState="setState"></res-model>
			</template>
			<n-button @click="cpd">计算</n-button>
		</n-form>
		<n-form class="form footer">
			<n-form-item v-for="(item, index) in cpdAA" :key="index" :label="item.name" >
				<view class="item">
					<span v-for="i in item.AA">{{ i.name }}: {{ i.count }}</span>
				</view>
			</n-form-item>
		</n-form>
	</view>
</template>

<script setup>
import store from '@/store'
import {
	ref
} from 'vue'
import {
	onLoad
} from '@dcloudio/uni-app'
import ResModel from './ResModel.vue'
const {
	addTask,
	delTask,
	getTasks
} = store.app

onLoad((options) => {
	task.value = getTasks[options.index]
	formState.value = task.value.map(item => {
		return {
			name: item,
			count: ''
		}
	})
})
const formState = ref([])
const task = ref([])
const cpdAA = ref([])

const setState = (index, val) => {
	formState.value[index].count = val
}

const cpd = () => {
	cpdAA.value = []
	const len = formState.value.length
	// 计算每人的平均支出
	const stateAA = formState.value.map(item => {
		let {
			name,
			count
		} = item
		count = Math.round((count / len)*1000)/1000
		return {
			name,
			count
		}
	})

	// 计算每人需向他人转账金额
	for (let i = 0; i < len; i++) {
		let AA = []
		for (let j = 0; j < len; j++) {
			if (stateAA[i].count < stateAA[j].count) {
				const aa = stateAA[j].count - stateAA[i].count
				AA.push({
					name: stateAA[j].name,
					count:  Math.round(aa*1000)/1000
				})

			}
		}
		cpdAA.value.push({
			name: stateAA[i].name,
			AA
		})
	}
}
</script>

<style scoped>
.logo {
	height: 200rpx;
	width: 200rpx;
	margin-top: 200rpx;
	margin-left: auto;
	margin-right: auto;
	margin-bottom: 50rpx;
}

.form {
	width: 90%;
	
}
.item{
	display: flex;
	flex-direction: row;
	justify-content: flex-start;
	align-items: center;
	flex-wrap: wrap;
}
span{
	padding: 5rpx;
}
p {
	margin-bottom: 20rpx;
}

</style>
